<template>
  <div class="relative ">
    <a-input-search ref="searchRef" v-if="search" v-model:value="address" @search="searchHandler" placeholder="搜索地址"
      enter-button class="mb-4"
      :class="{ 'px-24 absolute left-1/2 transform -translate-x-1/2 top-10 z-10': searchPosition == 'inside' }" />
    <div id="panel" v-show="showPanelBox"></div>
    <div class="h-96" ref="containerRef" :="$attrs" />
  </div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { createAMap } from './amap';
import { onMounted } from 'vue';
import { onUnmounted } from 'vue';
import { WatchStopHandle, toRaw } from 'vue';
import { useDebounceFn } from '@vueuse/core';


const {
  searchOverlays,
  showOverlay,
  clearPolygon,
  editPolygon,
  createPolygon,
  createPolygons,
  initAutoComplete,
  createMarker,
  createMarkerCustomContent,
  destoryMap,
  searchMap,
  initAMap,
  onChange,
  clearMarkers,
  closeEditPolygon,
  setCenter,
  setOptions,
  getMousetool
} = createAMap()
const containerRef = ref<HTMLDivElement>();
const address = ref('')
const searchRef = ref('');
const showPanelBox = ref(false)
const $props = withDefaults(
  defineProps<{
    polygons?: any[],
    value?: any,
    onlyShow?: boolean,
    satellite?: boolean,
    edit?: 'marker' | 'polygon',
    markers?: [],
    search?: boolean,
    searchPosition?: 'inside' | 'outside',
    rightActions?: { name: string, handler: Fn }[],
    zoom?: any,
    showPanel?: boolean,
  }>(),
  { satellite: true, searchPosition: 'inside', zoom: 18, showPanel: false }
)

const $emits = defineEmits<{
  (e: 'update:value', val: any): void
  (e: 'change', val: any): void
}>()
const stopWatch: WatchStopHandle[] = []
const markerUpdateCounter = ref(0);
const markerUpdateCounterFn = useDebounceFn(() => {
  markerUpdateCounter.value++
}, 200)
const searchHandler = async (query: string) => {
  if ($props.showPanel) showPanelBox.value = true;
  searchMap(query,
    (result: any) => {
      console.log(result)
      // 默认选择搜索的第一个作为经纬度信息
      if (result && result.info === 'OK' && result.poiList && result.pois) {
        address.value = result.poiList.pois[0].address;
      }
    });
};
onMounted(() => {
  initAMap(containerRef, $props).then(() => {
    $props.search && initAutoComplete(searchRef)
    stopWatch.push(watch(() => $props.markers, markers => {
      clearMarkers();
      if (markers) {
        markerUpdateCounterFn()
      }
      const extclass = markerUpdateCounter.value > -1 ? 'transform -translate-x-1/2 -translate-y-full' : '';
      markers?.forEach(({ lnglat, name = '', address = '', img = '', onClick, customContent }: any) => {
        if (name && !customContent) {
          name = `<div class='mt-1 mb-2 font-bold text-center whitespace-normal'>${name}</div>`
        }
        const content = `
        <div class="${extclass} w-28 p-3 relative bottom-2  bg-white/60 rounded-lg text-sm">${(img ? `<img src="${img.split(',')[0]}" class="object-contain w-full h-12 mx-auto mb-2"/>` : '') +
          `${name}<div class=" text-xs whitespace-normal">${address}</div>`
          }</div>`;
        if (lnglat && lnglat[0] && lnglat[1]) {
          let marker: AMap.Marker | undefined;
          if (!customContent) {
            marker = createMarker(lnglat, content)
          } else {
            marker = createMarkerCustomContent(lnglat, address, name)
          }
          onClick && marker?.on('click', onClick)
        }
      })
    }, {
      immediate: true,
      deep: true
    }),
      watch(() => $props.value, (val) => {
        if (!val || $props.edit != 'marker') {
          return;
        }
        if (val.poi) {
          address.value = val.poi
        }
        if (val.lnglat) {
          clearMarkers();
          createMarker(val.lnglat, undefined, true)
        }
      }, {
        immediate: true,
        deep: true
      }),
      watch(() => $props.polygons, (polygons) => {
        if (!polygons) {
          return;
        }
        polygons = toRaw(polygons)
        clearPolygon()

        // Method 1
        // let t0 = performance.now();

        createPolygons(polygons);

        // let t1 = performance.now();
        // console.log(`Method 1 took ${t1 - t0} milliseconds.`);

        // Method 2
        // t0 = performance.now();
        //
        // polygons.forEach(createPolygon);

        // t1 = performance.now();
        // console.log(`Method 2 took ${t1 - t0} milliseconds.`);

      }, {
        immediate: true,
      }),
      watch(() => $props.showPanel, (_val) => {
        showPanelBox.value = false;
      }, {
        immediate: true,
        deep: true
      }),
    )

    onChange((data) => {
      address.value = data.address
      $emits('update:value', data)
      $emits('change', data)
    })
  })
})
onUnmounted(() => {
  destoryMap();
  stopWatch.forEach(stop => stop());
  stopWatch.length = 0;
})
defineExpose({
  searchOverlays,
  showOverlay,
  editPolygon,
  createPolygon,
  createPolygons,
  closeEditPolygon,
  setCenter,
  setOptions,
  getMousetool
})
</script>
<script lang="ts">
export default {}
</script>
<script lang="ts">
</script>

<style>
.ant-input-group-wrapper {
  width: 400px;
  padding: 0px;
  height: 40px;
  border-radius: 8px;
  border: 1px solid #D9D9D9;
  overflow: hidden;
  box-sizing: border-box;
  background: #FFF;
}

.ant-input-group-wrapper span {
  height: 38px;
}

.ant-input-group-wrapper input {
  height: 100%;
  /* padding: 0px; */
  border: none;
  padding: 0px 11px;
}

.ant-input-group-wrapper .ant-btn {
  height: 38px;
  background: #FFF;
  border: none;
  border-left: 1px solid rgba(215, 215, 215, 0.2);
}

.ant-input-group-wrapper .ant-btn .anticon {
  /* line-height: 36px; */
  color: #888;
  font-size: 20px;
}

.ant-input-group-wrapper .ant-btn .anticon svg {
  margin-top: 10px;
}

.amap-container.h-full {
  height: 100%;
}

.ant-input-wrapper .ant-input {
  border: none;
}

#panel {
  position: absolute;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 20px;
  right: 70px;
  width: 314px;
  z-index: 100;
}
</style>
